import type { FormInstance } from 'antd';
import { Form } from 'antd';
import classNamesFn from 'classnames';
import { forwardRef, useImperativeHandle, useMemo, useState } from 'react';
import type { SizeInfo } from 'ym-design';
import { YmResizeObserver } from 'ym-design';
import QueryFilterContent from './QueryFilterContent';
import { YmQueryFilterProps } from './interface';
import { getSpanConfig } from './utils';

const QueryFilter = forwardRef<
  { getFormInstance: () => FormInstance },
  YmQueryFilterProps
>((props, ref) => {
  const {
    prefixCls = 'ym-query-filter',
    layout = 'horizontal',
    span, // 配置查询表单的每列所占格栅数
    labelWidth = 'auto',
    rootStyle,
    rootClassName,
    operColPosition = 'inline', // right
    labelCol, // 为了兼容旧版api,新版用labelWidth代替
    form,
    ...restProps
  } = props;

  let [queryFilterForm] = Form.useForm();
  if (form) {
    queryFilterForm = form;
  }

  const [filterWidth, setFilterWidth] = useState<number>(
    document.body.clientWidth,
  );

  // 监听的dom元素尺寸发生变化时
  const handleResize = (sizeInfo: SizeInfo, target: HTMLElement) => {
    // console.log('--sizeInfo--:', sizeInfo);
    const { width } = sizeInfo;
    if (target && width !== filterWidth) {
      setFilterWidth(width);
    }
  }; //, debounce(500);

  //{span,layout} 根据宽度计算出一行默认情况下格栅每列占位数，还可以根据searchcomps[i].colSpan自定义格栅每列占位数
  const spanSize: { span?: number; layout?: string } = useMemo(
    () => (filterWidth ? getSpanConfig(layout, filterWidth, span) : {}),
    [layout, filterWidth, span],
  );

  /** 计算最大宽度防止溢出换行, 与 formItemProps:{labelCol,wrapperCol} 设置没有区别，设置labelWidth只是为了让label对齐，该样式不作用于操作列 */
  const formItemFixStyle = useMemo(() => {
    if (spanSize.layout !== 'vertical') {
      let finalLabelWidth;
      if (labelWidth !== 'auto' && labelWidth) {
        finalLabelWidth =
          typeof labelWidth === 'string' ? labelWidth : labelWidth + 'px';
      } else if (labelCol?.style?.width) {
        const formLabelColWidth = labelCol?.style?.width;
        finalLabelWidth =
          typeof formLabelColWidth === 'string'
            ? formLabelColWidth
            : formLabelColWidth + 'px';
      }
      if (finalLabelWidth) {
        return {
          labelCol: {
            style: {
              flex: `0 0 ${finalLabelWidth}`,
            },
          },
          wrapperCol: {
            style: {
              maxWidth: `calc(100% - ${finalLabelWidth})`,
            },
          },
          style: {
            flexWrap: 'nowrap',
            margin: 0,
          },
        };
      } else {
        return {
          style: {
            flexWrap: 'nowrap',
            margin: 0,
          },
        };
      }
    }
    return {
      style: {
        flexWrap: 'nowrap',
      },
    };
  }, [spanSize?.layout, labelWidth, labelCol]);

  useImperativeHandle(ref, () => ({
    getFormInstance: () => queryFilterForm,
  }));

  return (
    <div className={classNamesFn(prefixCls, rootClassName)} style={rootStyle}>
      <YmResizeObserver
        isFullParent
        onResize={handleResize}
        rootClassName={`${prefixCls}-resize-content`}
      >
        <Form autoComplete="off" {...restProps} form={queryFilterForm}>
          <QueryFilterContent
            {...restProps}
            prefixCls={prefixCls}
            spanSize={spanSize}
            formItemFixStyle={formItemFixStyle}
            queryFilterFormInstance={queryFilterForm}
            operColPosition={operColPosition}
          />
        </Form>
      </YmResizeObserver>
    </div>
  );
});

export default QueryFilter;
